﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hive.Core;
using Hive.Bot.Tasks;

namespace Hive.Bot.Behaviours
{
    public class AttackEnemyBehavior: IBehaviour
    {
        public List<Tasks.ITask> GenerateTasks()
        {
            var result = new List<Tasks.ITask>();

            foreach (var ea in Env.EnemyAnts)
            {
                Squad s = new Squad(ea);
                var count = Env.MyAnts.Count * 0.1 + 1;
                for (int i = 0; i < count; i++)
                {
                    result.Add(new AttackEnemyTask(s));
                }
            }

            return result;
        }
    }

    public class Squad
    {
        Location destination;
        public Squad(Location destination)
        {
            this.destination = destination;
        }
        
        List<Ant> ants = new List<Ant>();
        public void Assign(Ant ant)
        {
            ants.Add(ant);
        }

        public Order Execute(Ant ant)
        {
            //strategy is following
            //we can trade equally
            //if we loose we try to move out of attack radius
            //if we win we move in (would be very nice to check all possibilities of enemy moves and moe accordingly to the most effective positioning)

            //Env.GetVisibilityOffsets
            var route = Env.Map.BuildPath(ant.Location, destination);

            if (route.Any())
            {
                return new Order()
                {
                    Destination = route.First(),
                    Ant = ant,
                    Efficiency = 0//CalculateEfficiency(ant)
                };
            }
            else
            {
                if (ant.Location == destination)
                {
                    return new Order()
                    {
                        Destination = ant.Location,
                        Ant = ant,
                        Efficiency = 0//CalculateEfficiency(ant)
                    };
                }
            }

            throw new ApplicationException(string.Format("Cannot move ant id {0} at {1} to {2}", ant.Id, ant.Location, destination));
        }

        IEnumerable<int> efficiencies;
        public IEnumerable<int> CalculateEfficiencies(IEnumerable<Ant> ants)
        {
            if (efficiencies == null)
            {
                efficiencies = ants.Select(a => (int)(MoveTask.GetEfficiencyByDistance(Env.Map.GetDistance(a.Location, destination)) * 1.1));
            }
            return efficiencies;
        }
    }
}
